package espacokidsadm.util;

import java.util.Iterator;
import javax.faces.application.FacesMessage;
import javax.faces.component.EditableValueHolder;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.Flash;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class JSFUtil {

    /**
   * Returns the current HTTP session.
   */
  public static HttpSession getHttpSession() {
    FacesContext facescontext = FacesContext.getCurrentInstance();
    HttpSession session = (HttpSession) facescontext.getExternalContext().getSession(true);
    return session;
  }
 
  /**
   * Returns the current servlet response object instance.
   */
  public static HttpServletResponse getHttpServletResponse() {
    FacesContext facescontext = FacesContext.getCurrentInstance();
    HttpServletResponse response=(HttpServletResponse)facescontext.getExternalContext().getResponse();
    return response;
  }
 
  /**
   * Returns the current servlet request object instance.
   */
  public static HttpServletRequest getHttpServletRequest() {
    FacesContext facescontext = FacesContext.getCurrentInstance();
    HttpServletRequest request=(HttpServletRequest)facescontext.getExternalContext().getRequest();
    return request;
  }
 
  /**
   * Returns the servlet context.
   */
  public static ServletContext getServletContext() {
    ServletContext context = getHttpSession().getServletContext();
    return context;
  }
 

  /**
   * Adds a SEVERE message.
   *
   * @param message The message.
   */
  public static void addErrorMessage(String message) {
    FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message);
    FacesContext context = FacesContext.getCurrentInstance();
      context.addMessage(null, facesMsg);
  }
  /**
   * Adds an INFO message.
   *
   * @param message The message.
   */
  public static void addInfoMessage(String message) {
    FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, message, message);
    FacesContext context = FacesContext.getCurrentInstance();
      context.addMessage(null, facesMsg);
  }
  /**
   * Adds a WARNING message.
   *
   * @param message The message.
   */
  public static void addWarningMessage(String message) {
    FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_WARN, message, message);
    FacesContext context = FacesContext.getCurrentInstance();
     context.addMessage(null, facesMsg);
  }
 
  /**
   * Removes all current messages held by the JSF framework.
   */
  @SuppressWarnings({ "rawtypes" }) //$NON-NLS-1$
  public static void resetMessages() {
    FacesContext context = FacesContext.getCurrentInstance();
      Iterator iter = context.getMessages();
      while (iter.hasNext()) {
        iter.next();
        iter.remove();
    }
  }
   
  public static String redirectPage(String pageWithExtention) {
      FacesContext.getCurrentInstance().getApplication().getNavigationHandler().handleNavigation(FacesContext.getCurrentInstance(), null, pageWithExtention);  
      return FacesContext.getCurrentInstance().getApplication().getNavigationHandler().toString(); 
  }
   
  public static String redirectPage(String pageWithExtention, String params) {
      FacesContext.getCurrentInstance().getApplication().getNavigationHandler().handleNavigation(FacesContext.getCurrentInstance(), null, pageWithExtention + "?" + params);  
      return FacesContext.getCurrentInstance().getApplication().getNavigationHandler().toString(); 
  }
  
  /**
	 * Limpa os dados dos componentes de edição e de seus filhos,
	 * recursivamente. Checa se o componente é instância de EditableValueHolder
	 * e 'reseta' suas propriedades.
	 * <p>
	 * Quando este método, por algum motivo, não funcionar, parta para ignorância
	 * e limpe o componente assim:
	 * <p><blockquote><pre>
	 * 	component.getChildren().clear()
	 * </pre></blockquote>
	 * :-)
	 */
	public static void cleanSubmittedValues(UIComponent component) {
		if (component instanceof EditableValueHolder) {
			EditableValueHolder evh = (EditableValueHolder) component;
			evh.setSubmittedValue(null);
			evh.setValue(null);
			evh.setLocalValueSet(false);
			evh.setValid(true);
		}
		if(component.getChildCount()>0){
			for (UIComponent child : component.getChildren()) {
				cleanSubmittedValues(child);
			}
		}
	}

	public static void cleanSubmittedValues(String componentName) {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		UIComponent component = facesContext.getViewRoot().findComponent(componentName);
		if (component != null)
			cleanSubmittedValues(component);
	}
	
	
	public static Flash flashScope (){
		return (FacesContext.getCurrentInstance().getExternalContext().getFlash());
	}
}
